<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" title="流程模型管理">
        <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
          <template #statusSlot="{ model, field }">
            <n-input v-model:value="model[field]" />
          </template>
        </BasicForm>
      </n-card>
    </div>

    <n-card :bordered="false" class="mt-4 proCard">
      <BasicTable :columns="columns" :request="loadDataTable" :row-key="(row) => row.id" ref="actionRef"
        :actionColumn="actionColumn" @update:checked-row-keys="onCheckedRow" id="moss-basicTable" :bordered="false">
        <template #tableTitle>
          <n-button type="primary" @click="navigateToRoute(0)">
            <template #icon>
              <n-icon>
                <PlusOutlined />
              </n-icon>
            </template>
            设计流程
          </n-button>
        </template>
        <template #action>
          <TableAction />
        </template>
      </BasicTable>
    </n-card>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, h, onMounted } from 'vue';
import { useMessage, useDialog } from 'naive-ui';
import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
import { BasicTable, TableAction } from '@/components/Table';
import { page, remove } from '@/api/flow/flowModel';
import { page as flowGroupPage } from '@/api/flow/flowGroup';
import { columns } from './columns';
import { DeleteOutlined, EditOutlined, PlusOutlined } from '@vicons/antd';
import { ResultEnum } from '@/enums/httpEnum';
const message = useMessage();
const actionRef = ref();
const dialog = useDialog();
const groupOptions = ref([]);
const typeOptions = ref([{ label: '工作流', value: 1 }, { label: '协同作战任务', value: 2 }]);
import { useRouter } from 'vue-router';
const router = useRouter();
/**
 * 表格查询参数定义
 */
const schemas: FormSchema[] = [
  /**查询参数*/
  {
    field: 'flowModelName',
    component: 'NInput',
    label: '流程模型名称',
    componentProps: {
      placeholder: '请输入流程模型名称',
    },
  },
  {
    field: 'flowModelGroup',
    component: 'NSelect',
    label: '状态',
    componentProps: {
      placeholder: '请选择流程分组',
      options: groupOptions,
    },
  },
  {
    field: 'flowModelType',
    component: 'NSelect',
    label: '状态',
    componentProps: {
      placeholder: '请选择流程类型',
      options: typeOptions,
    },
  },
];
/**
 * 表格查询注册
 */
const [register, { getFieldsValue }] = useForm({
  gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
  labelWidth: 120,
  schemas,
});
const actionColumn = reactive({
  width: 250,
  title: '操作',
  key: 'action',
  fixed: 'right',
  render(record) {
    return h(TableAction as any, {
      style: 'text',
      actions: createActions(record),
    });
  },
});

function createActions(record) {
  return [
    {
      label: '删除',
      type: 'error',
      // 配置 color 会覆盖 type
      color: 'red',
      icon: DeleteOutlined,
      onClick: handleDelete.bind(null, record),
      // 根据业务控制是否显示 isShow 和 auth 是并且关系
      ifShow: () => {
        return true;
      },
      // 根据权限控制是否显示: 有权限，会显示，支持多个
      //auth: ['basic_list'],
    },
    {
      label: '编辑',
      type: 'primary',
      icon: EditOutlined,
      onClick: handleEdit.bind(null, record),
      ifShow: () => {
        return true;
      },
      //auth: ['basic_list'],
    },
  ];
}
const loadDataTable = async (res: any) => {
  return await page({ ...getFieldsValue(), ...res });
};

function onCheckedRow(rowKeys: any[]) {
  console.log(rowKeys);
}

function reloadTable() {
  actionRef.value.reload();
}
/**
 * 查询
 */
function handleSubmit() {
  reloadTable();
}
/**
 * 重置查询
 */
function handleReset() {
  reloadTable();
}
/**
 * 新增编辑model
 * @param record
 * @param addStatus
 */
async function handleEdit(record: Recordable) {
  navigateToRoute(record.id);
}
/**
 * 删除确认
 * @param record
 */
function handleDelete(record: Recordable) {
  dialog.warning({
    title: '警告',
    content: `确定删除吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const data = await remove({ id: record.id });
      if (data.code !== ResultEnum.SUCCESS) {
        const resultMsg = data.data ? data.data : '';
        message.error(data.msg + '-' + resultMsg);
      }
      if (data.code === ResultEnum.SUCCESS) {
        message.success(data.msg);
        reloadTable();
      }
    },
  })
}

const navigateToRoute = (id) => {
  router.push({ name: 'flow-design', params: { id: id } });
}
onMounted(async () => {
  const group = await flowGroupPage({});
  groupOptions.value = group.records.map(item => ({ label: item.groupName, value: item.id }));
})
</script>

<style lang="less" scoped>
.moss-custom-table-param {
  padding: 0px 0px 15px 0px;
}

.moss-custom-table-param-end {
  text-align: end;
}
</style>
